import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  ArcElement,
} from 'chart.js';
import { Line, Bar, Doughnut } from 'react-chartjs-2';
import { useUserStore } from '../../store/userStore';

// 注册 Chart.js 组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  ArcElement
);

const CarbonTrendChart: React.FC = () => {
  const { activities } = useUserStore();
  
  // 处理数据
  const last7Days = Array.from({ length: 7 }, (_, i) => {
    const date = new Date();
    date.setDate(date.getDate() - i);
    return date.toLocaleDateString('zh-CN', { weekday: 'short' });
  }).reverse();
  
  const data = {
    labels: last7Days,
    datasets: [{
      label: '碳排放量 (kg)',
      data: last7Days.map(day => 
        activities
          .filter(a => {
            // 确保日期是Date对象
            const activityDate = a.date instanceof Date ? a.date : new Date(a.date);
            // 检查日期是否有效
            if (isNaN(activityDate.getTime())) return false;
            return activityDate.toLocaleDateString('zh-CN', { weekday: 'short' }) === day;
          })
          .reduce((sum, a) => sum + a.value, 0)
      ),
      borderColor: '#4CAF50',
      backgroundColor: 'rgba(76, 175, 80, 0.1)',
      tension: 0.4,
    }]
  };

  return (
    <div style={{ padding: '20px', background: 'white', borderRadius: '12px' }}>
      <h3>碳排放趋势</h3>
      <Line data={data} options={{ responsive: true }} />
    </div>
  );
};

const ActivityTypeChart: React.FC = () => {
  const { activities } = useUserStore();
  
  const typeData = {
    labels: ['交通', '能源', '食物', '废弃物'],
    datasets: [{
      data: ['transport', 'energy', 'food', 'waste'].map(type =>
        activities
          .filter(a => a.category === type)
          .reduce((sum, a) => sum + a.value, 0)
      ),
      backgroundColor: [
        '#FF9800',
        '#2196F3',
        '#4CAF50',
        '#F44336'
      ]
    }]
  };

  return (
    <div style={{ padding: '20px', background: 'white', borderRadius: '12px' }}>
      <h3>碳排放类型分布</h3>
      <Doughnut data={typeData} options={{ responsive: true }} />
    </div>
  );
};

const GreenEnergyChart: React.FC = () => {
  const { user } = useUserStore();
  
  const data = {
    labels: ['清洁能源', '传统能源'],
    datasets: [{
      data: [
        user?.planetState.energy.clean || 0,
        (user?.planetState.energy.total || 0) - (user?.planetState.energy.clean || 0)
      ],
      backgroundColor: ['#4CAF50', '#FF9800']
    }]
  };

  return (
    <div style={{ padding: '20px', background: 'white', borderRadius: '12px' }}>
      <h3>能源使用比例</h3>
      <Bar data={data} options={{ responsive: true }} />
    </div>
  );
};

export const Dashboard: React.FC = () => {
  const { user } = useUserStore();

  return (
    <div style={{ padding: '20px' }}>
      {/* 总览数据 */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
        gap: '20px',
        marginBottom: '30px'
      }}>
        <div style={{
          background: 'white',
          padding: '20px',
          borderRadius: '12px',
          textAlign: 'center'
        }}>
          <h4 style={{ margin: '0', color: '#666' }}>总碳足迹</h4>
          <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#4CAF50' }}>
            {user?.carbonFootprint.toFixed(2)} kg
          </div>
        </div>
        
        <div style={{
          background: 'white',
          padding: '20px',
          borderRadius: '12px',
          textAlign: 'center'
        }}>
          <h4 style={{ margin: '0', color: '#666' }}>绿色能量</h4>
          <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#2196F3' }}>
            {user?.greenEnergy} 点
          </div>
        </div>
        
        <div style={{
          background: 'white',
          padding: '20px',
          borderRadius: '12px',
          textAlign: 'center'
        }}>
          <h4 style={{ margin: '0', color: '#666' }}>星球健康度</h4>
          <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#FF9800' }}>
            {((1 - (user?.planetState.pollution || 0)) * 100).toFixed(1)}%
          </div>
        </div>
      </div>

      {/* 图表网格 */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
        gap: '20px'
      }}>
        <CarbonTrendChart />
        <ActivityTypeChart />
        <GreenEnergyChart />
      </div>
    </div>
  );
}; 